import config from '@/config.js'
import dateFormat from './DateFormat.js'

let _debounceTimeout = null,
	_throttleRunning = false

/**
 * 防抖
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms
 */
export const debounce = (fn, delay=500) => {
	clearTimeout(_debounceTimeout);
	_debounceTimeout = setTimeout(() => {
		fn();
	}, delay);
}
/**
 * 节流
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms
 */
export const throttle = (fn, delay=500) => {
	if(_throttleRunning){
		return;
	}
	_throttleRunning = true;
	fn();
	setTimeout(() => {
	    _throttleRunning = false;
	}, delay);
}
/**
 * toast
 */
export const msg = (title = '', param={}) => {
	if(!title) return;
	uni.showToast({
		title,
		duration: param.duration || 1500,
		mask: param.mask || false,
		icon: param.icon || 'none'
	});
}

/**
 * 检查登录
 * @return {Boolean}
 */
export const isLogin = (options={}) => {
	const token = uni.getStorageSync('uniIdToken');
	if(token){
		return true;
	}
	if(options.nav !== false){
		uni.navigateTo({
			url: '/pages/auth/login'
		})
	}
	return false;
}
/**
 * 获取页面栈
 * @param {Number} preIndex为1时获取上一页
 * @return {Object}
 */
export const prePage = (preIndex = 1) => {
	const pages = getCurrentPages();
	const prePage = pages[pages.length - (preIndex + 1)];

	return prePage.$vm;
}
/**
 * 格式化时间戳 Y-m-d H:i:s
 * @param {String} format Y-m-d H:i:s
 * @param {Number} timestamp 时间戳
 * @return {String}
 */
export const date = (format, timeStamp) => {
	if('' + timeStamp.length <= 10){
		timeStamp = + timeStamp * 1000;
	}else{
		timeStamp = + timeStamp;
	}
	let _date = new Date(timeStamp),
		Y = _date.getFullYear(),
		m = _date.getMonth() + 1,
		d = _date.getDate(),
		H = _date.getHours(),
		i = _date.getMinutes(),
		s = _date.getSeconds();

	m = m < 10 ? '0' + m : m;
	d = d < 10 ? '0' + d : d;
	H = H < 10 ? '0' + H : H;
	i = i < 10 ? '0' + i : i;
	s = s < 10 ? '0' + s : s;

	return format.replace(/[YmdHis]/g, key=>{
		return {Y,m,d,H,i,s}[key];
	});
}
//二维数组去重
export const getUnique = array => {
	let obj = {}
    return array.filter((item, index) => {
		let newItem = item + JSON.stringify(item)
		return obj.hasOwnProperty(newItem) ? false : obj[newItem] = true
	})
}
// 判断类型集合
export const checkStr = (str, type) => {
	switch (type) {
		case 'mobile': //手机号码
			return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
		case 'tel': //座机
			return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
		case 'card': //身份证
			return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
		case 'mobileCode': //6位数字验证码
			return /^[0-9]{6}$/.test(str)
		case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
			return /^([a-zA-Z0-9_]){6,18}$/.test(str)
		case 'payPwd': //支付密码 6位纯数字
			return /^[0-9]{6}$/.test(str)
		case 'postal': //邮政编码
			return /[1-9]\d{5}(?!\d)/.test(str);
		case 'QQ': //QQ号
			return /^[1-9][0-9]{4,9}$/.test(str);
		case 'email': //邮箱
			return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
		case 'money': //金额(小数点2位)
			return /^\d*(?:\.\d{0,2})?$/.test(str);
		case 'URL': //网址
			return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
		case 'IP': //IP
			return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
		case 'date': //日期时间
			return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/
				.test(str)
		case 'number': //数字
			return /^[0-9]$/.test(str);
		case 'english': //英文
			return /^[a-zA-Z]+$/.test(str);
		case 'chinese': //中文
			return /^[\\u4E00-\\u9FA5]+$/.test(str);
		case 'lower': //小写
			return /^[a-z]+$/.test(str);
		case 'upper': //大写
			return /^[A-Z]+$/.test(str);
		case 'HTML': //HTML标记
			return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
		default:
			return true;
	}
}

// 判断是否为空
export const isBlank = (val) => {
	if ((val == null || typeof(val) == "undefined") || (typeof(val) == "string" && (val == "" || val == "undefined" || val == "null"))) {
		return true;
	} else {
		return false;
	}
}

// 判断非空
export const isNotBlank = (val) => {
	return !isBlank(val);
}

// 返回
export const goBack = () => {
	uni.navigateBack();
}

// 跳转
export const myNavigateTo = url => {
	uni.navigateTo({
		url: url
	})
}

// 字符截取
export const mySubStr = (txt, len, type) => {
	if (isBlank(txt)) {
		return "";
	}
	if (isBlank(type)) {
		type = '...';
	}
	return txt.length > len ? (txt.substring(0, len) + type):txt;
}

// 日期相减
export const getNumberOfDays = (date1,date2) => {//获得天数
    //date1：开始日期，date2结束日期
    var a1 = Date.parse(new Date(Date.parse(date1.replace(/-/g,  "/"))));
    var a2 = Date.parse(new Date(Date.parse(date2.replace(/-/g,  "/"))));
    var day = parseInt((a2-a1)/ (1000 * 60 * 60 * 24));//核心：时间戳相减，然后除以天数
    return day
}

// 获取页面宽度
// val 倍率 0-1
export const getPageWidth = (val) => {
	if (isBlank(val)) {
		val = 1;
	}
	return uni.upx2px(750 * uni.getSystemInfoSync().windowWidth * val / uni.getSystemInfoSync().windowWidth);
}

////////////////////////////////////////////////////////////////////////////////
//
// parseTime(string aTime) - takes a string of time in the format HH:MM:SS
//                           and returns Javascript Date Object
//
////////////////////////////////////////////////////////////////////////////////
function parseTime(aTime) {
    var aDateTimeObject = 'none';
    if (aTime !== undefined && aTime.length) {
        aDateTimeObject = GMTTime();
        try {
            var theHour = parseInt(aTime.split(':')[0]);
            var theMinutes = parseInt(aTime.split(':')[1]);
            aDateTimeObject.setHours(theHour);
            aDateTimeObject.setMinutes(theMinutes);
        }
        catch (ex) {
        }
    }
    return aDateTimeObject;
}
////////////////////////////////////////////////////////////////////////////////
//
// GMTTime() - returns time adjusted to GMT (Universal Time)
//
////////////////////////////////////////////////////////////////////////////////
function GMTTime() {
    var aDate = new Date();
    var aDateAdjustedToGMTInMS = aDate.getTime() + (aDate.getTimezoneOffset() * 60 * 1000);
    return (new Date(aDateAdjustedToGMTInMS));
}

//打开第三方地图(后台地图使用BD09坐标)
export function openMap(latitude,longitude,name){
    let url = "";
    if (plus.os.name == "Android") {
        let hasBaiduMap = plus.runtime.isApplicationExist({
            pname: 'com.baidu.BaiduMap',
            action: 'baidumap://'
        });
        let hasAmap = plus.runtime.isApplicationExist({
            pname: 'com.autonavi.minimap',
            action: 'androidamap://'
        });
		// &coord_type=gcj02
        let urlBaiduMap = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&src=andr.baidu.openAPIdemo`
        urlBaiduMap = encodeURI(urlBaiduMap)
		let pointObj = bd_decrypt(longitude, latitude);
        let urlAmap = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=`+ pointObj.lat +`&lon=`+ pointObj.lng +`&dev=0`
        urlAmap = encodeURI(urlBaiduMap)
        if (hasAmap && hasBaiduMap) {
            plus.nativeUI.actionSheet({
                title: "选择地图应用",
                cancel: "取消",
                buttons: [{
                    title: "百度地图"
                }, {
                    title: "高德地图"
                }]
            }, function(e) {
                switch (e.index) {
                    case 1:
                        plus.runtime.openURL(urlBaiduMap);
                        break;
                    case 2:
                        plus.runtime.openURL(urlAmap);
                        break;
                }
            })
        } else if (hasAmap) {
            plus.runtime.openURL(urlAmap);
        } else if (hasBaiduMap) {
            plus.runtime.openURL(urlBaiduMap);
        } else {
            plus.nativeUI.alert("本机未安装指定的地图应用");
            // url = "geo:"+latitude+","+longitude+"?q=%e6%95%b0%e5%ad%97%e5%a4%a9%e5%a0%82";
            // plus.runtime.openURL(url); //如果是国外应用，应该优先使用这个，会启动google地图。这个接口不能统一坐标系，进入百度地图时会有偏差
        }
    } else {
        // iOS上获取本机是否安装了百度高德地图，需要在manifest里配置，在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加（如urlschemewhitelist:["iosamap","baidumap"]）
        plus.nativeUI.actionSheet({
            title: "选择地图应用",
            cancel: "取消",
			// {
			//     title: "Apple地图"
			// },
            buttons: [ {
                title: "百度地图"
            }, {
                title: "高德地图"
            }]
        }, function(e) {
            console.log("e.index: " + e.index);
            switch (e.index) {
                // case 1:
                //     url = `http://maps.apple.com/?q=%e6%95%b0%e5%ad%97%e5%a4%a9%e5%a0%82&ll=${latitude},${longitude}&spn=0.008766,0.019441`;
                //     break;
                case 1:
                    url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
                    break;
                case 2:
					let pointObj = bd_decrypt(longitude, latitude);
                    url = `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=`+ pointObj.lat +`&lon=`+ pointObj.lng +`&dev=0`
                    break;
                default:
                    break;
            }
            if (url != "") {
                url = encodeURI(url)
                plus.runtime.openURL(url, function(e) {
                    plus.nativeUI.alert("本机未安装指定的地图应用");
                });
            }
        })
    }
}

// 百度坐标转为高德坐标
export function bd_decrypt(bd_lng, bd_lat) {
    var X_PI = Math.PI * 3000.0 / 180.0;
    var x = bd_lng - 0.0065;
    var y = bd_lat - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
    var gg_lng = z * Math.cos(theta);
    var gg_lat = z * Math.sin(theta);
    return {lng: gg_lng, lat: gg_lat}
}

//高德坐标转百度（传入经度、纬度）
function gd_encrypt(gg_lng, gg_lat) {
    var X_PI = Math.PI * 3000.0 / 180.0;
    var x = gg_lng, y = gg_lat;
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI);
    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI);
    var bd_lng = z * Math.cos(theta) + 0.0065;
    var bd_lat = z * Math.sin(theta) + 0.006;
    return {
        bd_lat: bd_lat,
        bd_lng: bd_lng
    };
}

// 生成唯一id
export function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

export function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}

export function UrlSearch() {
	let name, value;
	// let str = 'http://iot.ztn-tech.com/m/index.html?companyId=2#/pages/login/login'
	let str = window.location.href; //取得整个地址栏
	let startIndex = str.indexOf('?')
	let endIndex = str.indexOf('#')
	str = str.substr(startIndex + 1, endIndex - 1 - startIndex); //取得所有参数   stringvar.substr(start [, length ]

	let arr = str.split('&'); //各个参数放到数组里
	for (let i = 0; i < arr.length; i++) {
		startIndex = arr[i].indexOf('=');
		if (startIndex > 0) {
			name = arr[i].substring(0, startIndex);
			value = arr[i].substr(startIndex + 1);
			this[name] = value;
		}
	}
}

export function showLoading(title, mask = true) {
	uni.showLoading({
		title: title,
		mask: mask,
	});
}

export function hideLoading() {
	uni.hideLoading();
}

export function showModal(title, content, showCancel = true, confirmText = '确认', cancelText = '取消', success, cancel) {
	uni.showModal({
		title: title,
		content: content,
		showCancel: showCancel,
		confirmText: confirmText,
		confirmColor: '#2d58cb',
		cancelText: cancelText,
		cancelColor: '#576B95',
		success: (res) => {
			if (res.confirm) {
				success()
			} else
			if (res.cancel) {
				cancel()
			}
		}
	});
}

export function showToast(title, icon = 'none', duration = 3000, mask = true) {
	uni.showToast({
		title: title,
		icon: icon,
		duration: duration,
		mask: mask,
	});
}

export function picPreview(index, arr, key) {
	if (arr.length == 0) return
	let isStringArr = typeof arr[0] == 'string'
	uni.previewImage({
		current: index,
		urls: isStringArr? arr:arr.map(item=>{
			key = key || 'url'
			return item[key]
		})
	})
}

export function friendly_time(vueInstance, time_stamp, format) {
	if (isBlank(format)) format = "yyyy-mm-dd hh:MM";
	var now_d = new Date();
	var now_time = now_d.getTime() / 1000; //获取当前时间的秒数
	var ct = now_time - time_stamp;
	var f_time,day = 0;
	if (ct < 0) {
		f_time = vueInstance.$u.timeFormat(time_stamp, 'hh:MM');
	}
	else if (ct < 60)
	{
		f_time = Math.floor(ct) + ' ' + vueInstance.i18n.secondsago;
	}
	else if (ct < 3600)
	{
		f_time = Math.floor(ct / 60) + ' ' + vueInstance.i18n.minutesago;
	}
	else if (ct < 86400)//一天
	{
		f_time = Math.floor(ct / 3600) + ' ' + vueInstance.i18n.hoursago;
	}
	else if (ct < 604800)//7天
	{
		day = Math.floor(ct / 86400);
		if (day < 2)
			f_time =  vueInstance.i18n.yesterday + ' ' + vueInstance.$u.timeFormat(time_stamp, 'hh:MM');
		else
			f_time = vueInstance.$u.timeFormat(time_stamp, format);
		// else if (day < 4)
		//     f_time = day + '天前';
	}
	else {
		f_time = vueInstance.$u.timeFormat(time_stamp, format);
	}
	return f_time;
}

export function html2Text(htmlTxt){
	if (!htmlTxt) return '';
	var reg = new RegExp("<.+?>","g");//匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
	var text = htmlTxt.replace(reg, "");//执行替换成空字符
	return text;
}

export function getFormatDate(date, format) {
	let df = new dateFormat();
	if (date) {
		df.setTime(isNaN(date)? new Date(Date.parse(date.replace(/-/g,  "/"))):date)
	}else {
		// 当前时间
		df.setTime()
	}
	return df.toString(format? format:"yyyy-0m-0d");
}

export const hasHttp = url => {
	if (!url) return
	if (url.indexOf('http') > -1) {
		return url
	}else {
		return config.file_url + url
	}
}

/**
 * 格式化图片id为图片读取地址
 * @param imageId
 */
export const formatImageIdUrl = (imageId, defaultImageShape = 'round') => {
	if (!imageId) {
		return config.server_pic_url + 'default.png'
	}
	const baseUrl = config.base_url
	if ((imageId + '').indexOf('http') > -1) {
		return imageId
	}else if (isNaN(imageId)) {
		return `${baseUrl}${imageId}`
	}
	return `${baseUrl}/jcApi/file/image/${imageId}?shape=${defaultImageShape}`
}

/**
 * 上传文件
 * @param url
 */
export const httpUpload = (url, filePath, formData = {}) => {
  return new Promise((resolve, reject) => {
    const accessToken = uni.getStorageSync('token')
    wx.uploadFile({
      url,
      filePath,
      name: 'file',
      header: {
        Authorization: accessToken
      },
      formData,
      timeout: 60000,
      success(res) {
        const data = JSON.parse(res.data) || {}
        resolve(data)
      },
      fail(res) {
        reject(res)
      }
    })
  })
}

/**
 * 开启分享功能
 */
export function openShare() {
  wx.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
}

/**
 * 获取授权
 */
export function authGet(scope) {
  return new Promise((resolve, reject) => {
    // 查询用户是否授权查询地理位置
    wx.getSetting().then((res) => {
      if (!res.authSetting[scope]) {
        // 没有授权，开始获取授权
        wx.authorize({
          scope
        })
          .then(() => {
            resolve()
          })
          .catch(() => {
            showModalshowModal({
              title: '提示',
              content: `${scope}授权失败`,
              showCancel: false
            })
            reject()
          })
      } else {
        resolve()
      }
    })
  })
}

export function listToTree(data, key) {
	if (!key) key = 'parentId'
	// * 先生成parent建立父子关系
	const obj = {};
	data.forEach((item) => {
		obj[item.id] = item;
	});
	// * obj -> {1001: {id: 1001, parentId: 0, name: 'AA'}, 1002: {...}}
	// console.log(obj, "obj")
	const parentList = [];
	data.forEach((item) => {
		const parent = obj[item[key]];
		if (parent) {
			// * 当前项有父节点
			parent.children = parent.children || [];
			parent.children.push(item);
		} else {
			// * 当前项没有父节点 -> 顶层
			parentList.push(item);
		}
	});
	return parentList;
}

/**
 * 获取动态表单code
 */
export function getFormCode(label) {
	let code = '',applyFormList = uni.getStorageSync('applyFormList')
	if (applyFormList) {
		applyFormList.forEach(item=>{
			if (item.dictLabel.indexOf(label) > -1) code = item.dictValue
		})
	}
	return code;
}

/**
 * 复制内容到剪贴板
 */
export function setClipboard(url, showClipboardToast = true, clipboardSuccess) {
	if (url) {
		showModal('跳转提示', '微信小程序无法跳转第三方链接，建议点击 "复制链接" 按钮，在浏览器中打开', true, '复制链接', '取消', (res) => {
			uni.setClipboardData({
				data: url,
				showToast: showClipboardToast,
				success: function () {
					clipboardSuccess()
				}
			});
		}, (res) => {})
	}
}
